<html lang="en-US">

<head>
    
<title>「连载十三」优化你的应用结构和实现Redis缓存 - 花落雨忧</title>

<meta property="og:title" content="「连载十三」优化你的应用结构和实现Redis缓存 - 花落雨忧">



    



    
    <meta property="description" content="之前就在想，不少教程或示例的代码设计都是一步到位的（也没问题）
但实际操作的读者真的能够理解透彻为什么吗？左思右想，有了今天这一章的内容，我认为实际经历过一遍印象会更加深刻
[&amp;hellip;] 在本章节，将介绍以下功能的整理：
[&amp;hellip;] 在规划阶段我们发现了一个问题，这是目前的伪代码：
[&amp;hellip;] if ! HasErrors() { if &amp;hellip;">
    <meta property="og:description" content="之前就在想，不少教程或示例的代码设计都是一步到位的（也没问题）
但实际操作的读者真的能够理解透彻为什么吗？左思右想，有了今天这一章的内容，我认为实际经历过一遍印象会更加深刻
[&amp;hellip;] 在本章节，将介绍以下功能的整理：
[&amp;hellip;] 在规划阶段我们发现了一个问题，这是目前的伪代码：
[&amp;hellip;] if ! HasErrors() { if &amp;hellip;">
    






<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1">

<link rel="shortcut icon" href="https://www.lican.asia/logo/logo.png" type="image/x-icon" />



<link rel="stylesheet" href="/css/style.min.css" />

<link rel="stylesheet" href="/css/reset.min.css" />




<script src="https://www.lican.asia/js/highlight.min.js"></script>

<script>
hljs.configure({ ignoreUnescapedHTML: true })
hljs.highlightAll();
</script>


<script src="https://www.lican.asia/js/jquery.min.js"></script>




<link href="https://www.lican.asia/css/hugo-code.min.css" rel="stylesheet" />



    <style>
        .post-content img {
            max-width: 400px;
        }
    </style>
</head>

<body id="period" class="home blog">
    <a class="skip-content" href="#main">Press "Enter" to skip to content</a>
    <div id="overflow-container" class="overflow-container">
        <header class="site-header" id="site-header" role="banner">
    <div class="max-width">
        <div id="title-container" class="title-container">
            <div id="site-title" class="site-title"><a href="/">花落雨忧</a></div>
            <p class="tagline">思所及 力所行 方为真.</p>
        </div>
        
        <div id="menu-primary-container" class="menu-primary-container">
            <div class="icon-container">
            </div>
            <div id="menu-primary" class="menu-container menu-primary" role="navigation">
                <nav class="menu">
                    <ul id="menu-primary-items" class="menu-primary-items">
                        
                        
                        <li id="menu-item-0"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/posts" aria-current="page" tabindex="0">首页</a></li>
                        
                        <li id="menu-item-1"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/tech/" aria-current="page" tabindex="1">技术文档</a></li>
                        
                        <li id="menu-item-2"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/article/" aria-current="page" tabindex="2">文章</a></li>
                        
                        <li id="menu-item-3"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/project/" aria-current="page" tabindex="3">项目</a></li>
                        
                        <li id="menu-item-4"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/about/" aria-current="page" tabindex="4">关于</a></li>
                        
                    </ul>
                </nav>
            </div>
        </div>
    </div>
</header>

        <div id="primary-container" class="primary-container">
            <div class="max-width">
                <section id="main" class="main" role="main">
                    <div id="loop-container" class="loop-container">
                        <div
                            class="post type-post status-publish format-standard hentry entry">
                            <article>
                                <div class="post-container">
                                    <div class="post-header">
                                        <h2 class="post-title">
                                            <a href="/posts/posts/go/gin/2018-06-02-application-redis/">「连载十三」优化你的应用结构和实现Redis缓存</a>
                                        </h2>
                                        
                                        <div class="post-byline">Published on
                                            <a class="date" href="javascript:;">2018/06/02</a>
                                            
                                            
                                            
                                            By 
                                            <a class="author" href="javascript:;">煎鱼</a></div>
                                            
                                        
                                    </div>
                                    <div class="post-content">
                                        <h2 id="前言">前言</h2>
<p>之前就在想，不少教程或示例的代码设计都是一步到位的（也没问题）</p>
<p>但实际操作的读者真的能够理解透彻为什么吗？左思右想，有了今天这一章的内容，我认为实际经历过一遍印象会更加深刻</p>
<h2 id="本文目标">本文目标</h2>
<p>在本章节，将介绍以下功能的整理：</p>
<ul>
<li>抽离、分层业务逻辑：减轻 routers.go 内的 api 方法的逻辑（但本文暂不分层 repository，这块逻辑还不重）。</li>
<li>增加容错性：对 gorm 的错误进行判断。</li>
<li>Redis 缓存：对获取数据类的接口增加缓存设置。</li>
<li>减少重复冗余代码。</li>
</ul>
<h2 id="问题在哪">问题在哪？</h2>
<p>在规划阶段我们发现了一个问题，这是目前的伪代码：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">if</span> ! <span style="color:#a6e22e">HasErrors</span>() {
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">ExistArticleByID</span>(<span style="color:#a6e22e">id</span>) {
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">DeleteArticle</span>(<span style="color:#a6e22e">id</span>)
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">code</span> = <span style="color:#a6e22e">e</span>.<span style="color:#a6e22e">SUCCESS</span>
</span></span><span style="display:flex;"><span>	} <span style="color:#66d9ef">else</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">code</span> = <span style="color:#a6e22e">e</span>.<span style="color:#a6e22e">ERROR_NOT_EXIST_ARTICLE</span>
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>} <span style="color:#66d9ef">else</span> {
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">for</span> <span style="color:#a6e22e">_</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#66d9ef">range</span> <span style="color:#a6e22e">valid</span>.<span style="color:#a6e22e">Errors</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">logging</span>.<span style="color:#a6e22e">Info</span>(<span style="color:#a6e22e">err</span>.<span style="color:#a6e22e">Key</span>, <span style="color:#a6e22e">err</span>.<span style="color:#a6e22e">Message</span>)
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">c</span>.<span style="color:#a6e22e">JSON</span>(<span style="color:#a6e22e">http</span>.<span style="color:#a6e22e">StatusOK</span>, <span style="color:#a6e22e">gin</span>.<span style="color:#a6e22e">H</span>{
</span></span><span style="display:flex;"><span>	<span style="color:#e6db74">&#34;code&#34;</span>: <span style="color:#a6e22e">code</span>,
</span></span><span style="display:flex;"><span>	<span style="color:#e6db74">&#34;msg&#34;</span>:  <span style="color:#a6e22e">e</span>.<span style="color:#a6e22e">GetMsg</span>(<span style="color:#a6e22e">code</span>),
</span></span><span style="display:flex;"><span>	<span style="color:#e6db74">&#34;data&#34;</span>: make(<span style="color:#66d9ef">map</span>[<span style="color:#66d9ef">string</span>]<span style="color:#66d9ef">string</span>),
</span></span><span style="display:flex;"><span>})
</span></span></code></pre></div><p>如果加上规划内的功能逻辑呢，伪代码会变成：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">if</span> ! <span style="color:#a6e22e">HasErrors</span>() {
</span></span><span style="display:flex;"><span>    <span style="color:#a6e22e">exists</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">ExistArticleByID</span>(<span style="color:#a6e22e">id</span>)
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">==</span> <span style="color:#66d9ef">nil</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> <span style="color:#a6e22e">exists</span> {
</span></span><span style="display:flex;"><span>    		<span style="color:#a6e22e">err</span> = <span style="color:#a6e22e">DeleteArticle</span>(<span style="color:#a6e22e">id</span>)
</span></span><span style="display:flex;"><span>    		<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">==</span> <span style="color:#66d9ef">nil</span> {
</span></span><span style="display:flex;"><span>    		    <span style="color:#a6e22e">code</span> = <span style="color:#a6e22e">e</span>.<span style="color:#a6e22e">SUCCESS</span>
</span></span><span style="display:flex;"><span>    		} <span style="color:#66d9ef">else</span> {
</span></span><span style="display:flex;"><span>    		    <span style="color:#a6e22e">code</span> = <span style="color:#a6e22e">e</span>.<span style="color:#a6e22e">ERROR_XXX</span>
</span></span><span style="display:flex;"><span>    		}
</span></span><span style="display:flex;"><span>    	} <span style="color:#66d9ef">else</span> {
</span></span><span style="display:flex;"><span>    		<span style="color:#a6e22e">code</span> = <span style="color:#a6e22e">e</span>.<span style="color:#a6e22e">ERROR_NOT_EXIST_ARTICLE</span>
</span></span><span style="display:flex;"><span>    	}
</span></span><span style="display:flex;"><span>    } <span style="color:#66d9ef">else</span> {
</span></span><span style="display:flex;"><span>        <span style="color:#a6e22e">code</span> = <span style="color:#a6e22e">e</span>.<span style="color:#a6e22e">ERROR_XXX</span>
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>} <span style="color:#66d9ef">else</span> {
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">for</span> <span style="color:#a6e22e">_</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#66d9ef">range</span> <span style="color:#a6e22e">valid</span>.<span style="color:#a6e22e">Errors</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">logging</span>.<span style="color:#a6e22e">Info</span>(<span style="color:#a6e22e">err</span>.<span style="color:#a6e22e">Key</span>, <span style="color:#a6e22e">err</span>.<span style="color:#a6e22e">Message</span>)
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">c</span>.<span style="color:#a6e22e">JSON</span>(<span style="color:#a6e22e">http</span>.<span style="color:#a6e22e">StatusOK</span>, <span style="color:#a6e22e">gin</span>.<span style="color:#a6e22e">H</span>{
</span></span><span style="display:flex;"><span>	<span style="color:#e6db74">&#34;code&#34;</span>: <span style="color:#a6e22e">code</span>,
</span></span><span style="display:flex;"><span>	<span style="color:#e6db74">&#34;msg&#34;</span>:  <span style="color:#a6e22e">e</span>.<span style="color:#a6e22e">GetMsg</span>(<span style="color:#a6e22e">code</span>),
</span></span><span style="display:flex;"><span>	<span style="color:#e6db74">&#34;data&#34;</span>: make(<span style="color:#66d9ef">map</span>[<span style="color:#66d9ef">string</span>]<span style="color:#66d9ef">string</span>),
</span></span><span style="display:flex;"><span>})
</span></span></code></pre></div><p>如果缓存的逻辑也加进来，后面慢慢不断的迭代，岂不是会变成如下图一样？</p>
<p><img src="https://coolshell.cn/wp-content/uploads/2017/04/IMG_7411.jpg" alt="image"></p>
<p>现在我们发现了问题，应及时解决这个代码结构问题，同时把代码写的清晰、漂亮、易读易改也是一个重要指标</p>
<h2 id="如何改">如何改？</h2>
<p>在左耳朵耗子的文章中，这类代码被称为 “箭头型” 代码，有如下几个问题：</p>
<p>1、我的显示器不够宽，箭头型代码缩进太狠了，需要我来回拉水平滚动条，这让我在读代码的时候，相当的不舒服</p>
<p>2、除了宽度外还有长度，有的代码的 if-else 里的 if-else 里的 if-else 的代码太多，读到中间你都不知道中间的代码是经过了什么样的层层检查才来到这里的</p>
<p>总而言之，“箭头型代码”如果嵌套太多，代码太长的话，会相当容易让维护代码的人（包括自己）迷失在代码中，因为看到最内层的代码时，你已经不知道前面的那一层一层的条件判断是什么样的，代码是怎么运行到这里的，所以，箭头型代码是非常难以维护和 Debug 的。</p>
<p>简单的来说，就是<strong>让出错的代码先返回，前面把所有的错误判断全判断掉，然后就剩下的就是正常的代码了</strong></p>
<p>（注意：本段引用自耗子哥的 <a href="https://coolshell.cn/articles/17757.html">如何重构“箭头型”代码</a>，建议细细品尝）</p>
<h2 id="落实">落实</h2>
<p>本项目将对既有代码进行优化和实现缓存，希望你习得方法并对其他地方也进行优化</p>
<p>第一步：完成 Redis 的基础设施建设（需要你先装好 Redis）</p>
<p>第二步：对现有代码进行拆解、分层（不会贴上具体步骤的代码，希望你能够实操一波，加深理解 🤔）</p>
<h3 id="redis">Redis</h3>
<h4 id="一配置">一、配置</h4>
<p>打开 conf/app.ini 文件，新增配置：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-ini" data-lang="ini"><span style="display:flex;"><span><span style="color:#a6e22e">...</span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">[redis]</span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">Host</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">127.0.0.1:6379</span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">Password</span> <span style="color:#f92672">=</span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">MaxIdle</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">30</span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">MaxActive</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">30</span>
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">IdleTimeout</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">200</span>
</span></span></code></pre></div><h4 id="二缓存-prefix">二、缓存 Prefix</h4>
<p>打开 pkg/e 目录，新建 cache.go，写入内容：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#f92672">package</span> <span style="color:#a6e22e">e</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">const</span> (
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">CACHE_ARTICLE</span> = <span style="color:#e6db74">&#34;ARTICLE&#34;</span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">CACHE_TAG</span>     = <span style="color:#e6db74">&#34;TAG&#34;</span>
</span></span><span style="display:flex;"><span>)
</span></span></code></pre></div><h4 id="三缓存-key">三、缓存 Key</h4>
<p>（1）、打开 service 目录，新建 cache_service/article.go</p>
<p>写入内容：<a href="https://github.com/EDDYCJY/go-gin-example/blob/master/service/cache_service/article.go">传送门</a></p>
<p>（2）、打开 service 目录，新建 cache_service/tag.go</p>
<p>写入内容：<a href="https://github.com/EDDYCJY/go-gin-example/blob/master/service/cache_service/tag.go">传送门</a></p>
<p>这一部分主要是编写获取缓存 KEY 的方法，直接参考传送门即可</p>
<h4 id="四redis-工具包">四、Redis 工具包</h4>
<p>打开 pkg 目录，新建 gredis/redis.go，写入内容：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#f92672">package</span> <span style="color:#a6e22e">gredis</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#f92672">import</span> (
</span></span><span style="display:flex;"><span>	<span style="color:#e6db74">&#34;encoding/json&#34;</span>
</span></span><span style="display:flex;"><span>	<span style="color:#e6db74">&#34;time&#34;</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#e6db74">&#34;github.com/gomodule/redigo/redis&#34;</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#e6db74">&#34;github.com/EDDYCJY/go-gin-example/pkg/setting&#34;</span>
</span></span><span style="display:flex;"><span>)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">var</span> <span style="color:#a6e22e">RedisConn</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">redis</span>.<span style="color:#a6e22e">Pool</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">Setup</span>() <span style="color:#66d9ef">error</span> {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">RedisConn</span> = <span style="color:#f92672">&amp;</span><span style="color:#a6e22e">redis</span>.<span style="color:#a6e22e">Pool</span>{
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">MaxIdle</span>:     <span style="color:#a6e22e">setting</span>.<span style="color:#a6e22e">RedisSetting</span>.<span style="color:#a6e22e">MaxIdle</span>,
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">MaxActive</span>:   <span style="color:#a6e22e">setting</span>.<span style="color:#a6e22e">RedisSetting</span>.<span style="color:#a6e22e">MaxActive</span>,
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">IdleTimeout</span>: <span style="color:#a6e22e">setting</span>.<span style="color:#a6e22e">RedisSetting</span>.<span style="color:#a6e22e">IdleTimeout</span>,
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">Dial</span>: <span style="color:#66d9ef">func</span>() (<span style="color:#a6e22e">redis</span>.<span style="color:#a6e22e">Conn</span>, <span style="color:#66d9ef">error</span>) {
</span></span><span style="display:flex;"><span>			<span style="color:#a6e22e">c</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">redis</span>.<span style="color:#a6e22e">Dial</span>(<span style="color:#e6db74">&#34;tcp&#34;</span>, <span style="color:#a6e22e">setting</span>.<span style="color:#a6e22e">RedisSetting</span>.<span style="color:#a6e22e">Host</span>)
</span></span><span style="display:flex;"><span>			<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
</span></span><span style="display:flex;"><span>				<span style="color:#66d9ef">return</span> <span style="color:#66d9ef">nil</span>, <span style="color:#a6e22e">err</span>
</span></span><span style="display:flex;"><span>			}
</span></span><span style="display:flex;"><span>			<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">setting</span>.<span style="color:#a6e22e">RedisSetting</span>.<span style="color:#a6e22e">Password</span> <span style="color:#f92672">!=</span> <span style="color:#e6db74">&#34;&#34;</span> {
</span></span><span style="display:flex;"><span>				<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">_</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">c</span>.<span style="color:#a6e22e">Do</span>(<span style="color:#e6db74">&#34;AUTH&#34;</span>, <span style="color:#a6e22e">setting</span>.<span style="color:#a6e22e">RedisSetting</span>.<span style="color:#a6e22e">Password</span>); <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
</span></span><span style="display:flex;"><span>					<span style="color:#a6e22e">c</span>.<span style="color:#a6e22e">Close</span>()
</span></span><span style="display:flex;"><span>					<span style="color:#66d9ef">return</span> <span style="color:#66d9ef">nil</span>, <span style="color:#a6e22e">err</span>
</span></span><span style="display:flex;"><span>				}
</span></span><span style="display:flex;"><span>			}
</span></span><span style="display:flex;"><span>			<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">c</span>, <span style="color:#a6e22e">err</span>
</span></span><span style="display:flex;"><span>		},
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">TestOnBorrow</span>: <span style="color:#66d9ef">func</span>(<span style="color:#a6e22e">c</span> <span style="color:#a6e22e">redis</span>.<span style="color:#a6e22e">Conn</span>, <span style="color:#a6e22e">t</span> <span style="color:#a6e22e">time</span>.<span style="color:#a6e22e">Time</span>) <span style="color:#66d9ef">error</span> {
</span></span><span style="display:flex;"><span>			<span style="color:#a6e22e">_</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">c</span>.<span style="color:#a6e22e">Do</span>(<span style="color:#e6db74">&#34;PING&#34;</span>)
</span></span><span style="display:flex;"><span>			<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">err</span>
</span></span><span style="display:flex;"><span>		},
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">return</span> <span style="color:#66d9ef">nil</span>
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">Set</span>(<span style="color:#a6e22e">key</span> <span style="color:#66d9ef">string</span>, <span style="color:#a6e22e">data</span> <span style="color:#66d9ef">interface</span>{}, <span style="color:#a6e22e">time</span> <span style="color:#66d9ef">int</span>) <span style="color:#66d9ef">error</span> {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">conn</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">RedisConn</span>.<span style="color:#a6e22e">Get</span>()
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">defer</span> <span style="color:#a6e22e">conn</span>.<span style="color:#a6e22e">Close</span>()
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">value</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">json</span>.<span style="color:#a6e22e">Marshal</span>(<span style="color:#a6e22e">data</span>)
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">err</span>
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">_</span>, <span style="color:#a6e22e">err</span> = <span style="color:#a6e22e">conn</span>.<span style="color:#a6e22e">Do</span>(<span style="color:#e6db74">&#34;SET&#34;</span>, <span style="color:#a6e22e">key</span>, <span style="color:#a6e22e">value</span>)
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">err</span>
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">_</span>, <span style="color:#a6e22e">err</span> = <span style="color:#a6e22e">conn</span>.<span style="color:#a6e22e">Do</span>(<span style="color:#e6db74">&#34;EXPIRE&#34;</span>, <span style="color:#a6e22e">key</span>, <span style="color:#a6e22e">time</span>)
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">err</span>
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">return</span> <span style="color:#66d9ef">nil</span>
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">Exists</span>(<span style="color:#a6e22e">key</span> <span style="color:#66d9ef">string</span>) <span style="color:#66d9ef">bool</span> {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">conn</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">RedisConn</span>.<span style="color:#a6e22e">Get</span>()
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">defer</span> <span style="color:#a6e22e">conn</span>.<span style="color:#a6e22e">Close</span>()
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">exists</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">redis</span>.<span style="color:#a6e22e">Bool</span>(<span style="color:#a6e22e">conn</span>.<span style="color:#a6e22e">Do</span>(<span style="color:#e6db74">&#34;EXISTS&#34;</span>, <span style="color:#a6e22e">key</span>))
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#66d9ef">return</span> <span style="color:#66d9ef">false</span>
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">exists</span>
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">Get</span>(<span style="color:#a6e22e">key</span> <span style="color:#66d9ef">string</span>) ([]<span style="color:#66d9ef">byte</span>, <span style="color:#66d9ef">error</span>) {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">conn</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">RedisConn</span>.<span style="color:#a6e22e">Get</span>()
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">defer</span> <span style="color:#a6e22e">conn</span>.<span style="color:#a6e22e">Close</span>()
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">reply</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">redis</span>.<span style="color:#a6e22e">Bytes</span>(<span style="color:#a6e22e">conn</span>.<span style="color:#a6e22e">Do</span>(<span style="color:#e6db74">&#34;GET&#34;</span>, <span style="color:#a6e22e">key</span>))
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#66d9ef">return</span> <span style="color:#66d9ef">nil</span>, <span style="color:#a6e22e">err</span>
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">reply</span>, <span style="color:#66d9ef">nil</span>
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">Delete</span>(<span style="color:#a6e22e">key</span> <span style="color:#66d9ef">string</span>) (<span style="color:#66d9ef">bool</span>, <span style="color:#66d9ef">error</span>) {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">conn</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">RedisConn</span>.<span style="color:#a6e22e">Get</span>()
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">defer</span> <span style="color:#a6e22e">conn</span>.<span style="color:#a6e22e">Close</span>()
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">redis</span>.<span style="color:#a6e22e">Bool</span>(<span style="color:#a6e22e">conn</span>.<span style="color:#a6e22e">Do</span>(<span style="color:#e6db74">&#34;DEL&#34;</span>, <span style="color:#a6e22e">key</span>))
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">LikeDeletes</span>(<span style="color:#a6e22e">key</span> <span style="color:#66d9ef">string</span>) <span style="color:#66d9ef">error</span> {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">conn</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">RedisConn</span>.<span style="color:#a6e22e">Get</span>()
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">defer</span> <span style="color:#a6e22e">conn</span>.<span style="color:#a6e22e">Close</span>()
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">keys</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">redis</span>.<span style="color:#a6e22e">Strings</span>(<span style="color:#a6e22e">conn</span>.<span style="color:#a6e22e">Do</span>(<span style="color:#e6db74">&#34;KEYS&#34;</span>, <span style="color:#e6db74">&#34;*&#34;</span><span style="color:#f92672">+</span><span style="color:#a6e22e">key</span><span style="color:#f92672">+</span><span style="color:#e6db74">&#34;*&#34;</span>))
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">err</span>
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">for</span> <span style="color:#a6e22e">_</span>, <span style="color:#a6e22e">key</span> <span style="color:#f92672">:=</span> <span style="color:#66d9ef">range</span> <span style="color:#a6e22e">keys</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">_</span>, <span style="color:#a6e22e">err</span> = <span style="color:#a6e22e">Delete</span>(<span style="color:#a6e22e">key</span>)
</span></span><span style="display:flex;"><span>		<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
</span></span><span style="display:flex;"><span>			<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">err</span>
</span></span><span style="display:flex;"><span>		}
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">return</span> <span style="color:#66d9ef">nil</span>
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>在这里我们做了一些基础功能封装</p>
<p>1、设置 RedisConn 为 redis.Pool（连接池）并配置了它的一些参数：</p>
<ul>
<li>
<p>Dial：提供创建和配置应用程序连接的一个函数</p>
</li>
<li>
<p>TestOnBorrow：可选的应用程序检查健康功能</p>
</li>
<li>
<p>MaxIdle：最大空闲连接数</p>
</li>
<li>
<p>MaxActive：在给定时间内，允许分配的最大连接数（当为零时，没有限制）</p>
</li>
<li>
<p>IdleTimeout：在给定时间内将会保持空闲状态，若到达时间限制则关闭连接（当为零时，没有限制）</p>
</li>
</ul>
<p>2、封装基础方法</p>
<p>文件内包含 Set、Exists、Get、Delete、LikeDeletes 用于支撑目前的业务逻辑，而在里面涉及到了如方法：</p>
<p>（1）<code>RedisConn.Get()</code>：在连接池中获取一个活跃连接</p>
<p>（2）<code>conn.Do(commandName string, args ...interface{})</code>：向 Redis 服务器发送命令并返回收到的答复</p>
<p>（3）<code>redis.Bool(reply interface{}, err error)</code>：将命令返回转为布尔值</p>
<p>（4）<code>redis.Bytes(reply interface{}, err error)</code>：将命令返回转为 Bytes</p>
<p>（5）<code>redis.Strings(reply interface{}, err error)</code>：将命令返回转为 []string</p>
<p>在 <a href="https://godoc.org/github.com/gomodule/redigo/redis">redigo</a> 中包含大量类似的方法，万变不离其宗，建议熟悉其使用规则和 <a href="http://doc.redisfans.com/index.html">Redis 命令</a> 即可</p>
<p>到这里为止，Redis 就可以愉快的调用啦。另外受篇幅限制，这块的深入讲解会另外开设！</p>
<h3 id="拆解分层">拆解、分层</h3>
<p>在先前规划中，引出几个方法去优化我们的应用结构</p>
<ul>
<li>错误提前返回</li>
<li>统一返回方法</li>
<li>抽离 Service，减轻 routers/api 的逻辑，进行分层</li>
<li>增加 gorm 错误判断，让错误提示更明确（增加内部错误码）</li>
</ul>
<h4 id="编写返回方法">编写返回方法</h4>
<p>要让错误提前返回，c.JSON 的侵入是不可避免的，但是可以让其更具可变性，指不定哪天就变 XML 了呢？</p>
<p>1、打开 pkg 目录，新建 app/request.go，写入文件内容：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#f92672">package</span> <span style="color:#a6e22e">app</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#f92672">import</span> (
</span></span><span style="display:flex;"><span>	<span style="color:#e6db74">&#34;github.com/astaxie/beego/validation&#34;</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#e6db74">&#34;github.com/EDDYCJY/go-gin-example/pkg/logging&#34;</span>
</span></span><span style="display:flex;"><span>)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">MarkErrors</span>(<span style="color:#a6e22e">errors</span> []<span style="color:#f92672">*</span><span style="color:#a6e22e">validation</span>.<span style="color:#a6e22e">Error</span>) {
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">for</span> <span style="color:#a6e22e">_</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#66d9ef">range</span> <span style="color:#a6e22e">errors</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">logging</span>.<span style="color:#a6e22e">Info</span>(<span style="color:#a6e22e">err</span>.<span style="color:#a6e22e">Key</span>, <span style="color:#a6e22e">err</span>.<span style="color:#a6e22e">Message</span>)
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">return</span>
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>2、打开 pkg 目录，新建 app/response.go，写入文件内容：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#f92672">package</span> <span style="color:#a6e22e">app</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#f92672">import</span> (
</span></span><span style="display:flex;"><span>	<span style="color:#e6db74">&#34;github.com/gin-gonic/gin&#34;</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#e6db74">&#34;github.com/EDDYCJY/go-gin-example/pkg/e&#34;</span>
</span></span><span style="display:flex;"><span>)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">Gin</span> <span style="color:#66d9ef">struct</span> {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">C</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">gin</span>.<span style="color:#a6e22e">Context</span>
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">func</span> (<span style="color:#a6e22e">g</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">Gin</span>) <span style="color:#a6e22e">Response</span>(<span style="color:#a6e22e">httpCode</span>, <span style="color:#a6e22e">errCode</span> <span style="color:#66d9ef">int</span>, <span style="color:#a6e22e">data</span> <span style="color:#66d9ef">interface</span>{}) {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">g</span>.<span style="color:#a6e22e">C</span>.<span style="color:#a6e22e">JSON</span>(<span style="color:#a6e22e">httpCode</span>, <span style="color:#a6e22e">gin</span>.<span style="color:#a6e22e">H</span>{
</span></span><span style="display:flex;"><span>		<span style="color:#e6db74">&#34;code&#34;</span>: <span style="color:#a6e22e">errCode</span>,
</span></span><span style="display:flex;"><span>		<span style="color:#e6db74">&#34;msg&#34;</span>:  <span style="color:#a6e22e">e</span>.<span style="color:#a6e22e">GetMsg</span>(<span style="color:#a6e22e">errCode</span>),
</span></span><span style="display:flex;"><span>		<span style="color:#e6db74">&#34;data&#34;</span>: <span style="color:#a6e22e">data</span>,
</span></span><span style="display:flex;"><span>	})
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">return</span>
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>这样子以后如果要变动，直接改动 app 包内的方法即可</p>
<h4 id="修改既有逻辑">修改既有逻辑</h4>
<p>打开 routers/api/v1/article.go，查看修改 GetArticle 方法后的代码为：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">GetArticle</span>(<span style="color:#a6e22e">c</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">gin</span>.<span style="color:#a6e22e">Context</span>) {
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">appG</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">Gin</span>{<span style="color:#a6e22e">c</span>}
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">id</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">com</span>.<span style="color:#a6e22e">StrTo</span>(<span style="color:#a6e22e">c</span>.<span style="color:#a6e22e">Param</span>(<span style="color:#e6db74">&#34;id&#34;</span>)).<span style="color:#a6e22e">MustInt</span>()
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">valid</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">validation</span>.<span style="color:#a6e22e">Validation</span>{}
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">valid</span>.<span style="color:#a6e22e">Min</span>(<span style="color:#a6e22e">id</span>, <span style="color:#ae81ff">1</span>, <span style="color:#e6db74">&#34;id&#34;</span>).<span style="color:#a6e22e">Message</span>(<span style="color:#e6db74">&#34;ID必须大于0&#34;</span>)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">valid</span>.<span style="color:#a6e22e">HasErrors</span>() {
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">app</span>.<span style="color:#a6e22e">MarkErrors</span>(<span style="color:#a6e22e">valid</span>.<span style="color:#a6e22e">Errors</span>)
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">appG</span>.<span style="color:#a6e22e">Response</span>(<span style="color:#a6e22e">http</span>.<span style="color:#a6e22e">StatusOK</span>, <span style="color:#a6e22e">e</span>.<span style="color:#a6e22e">INVALID_PARAMS</span>, <span style="color:#66d9ef">nil</span>)
</span></span><span style="display:flex;"><span>		<span style="color:#66d9ef">return</span>
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">articleService</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">article_service</span>.<span style="color:#a6e22e">Article</span>{<span style="color:#a6e22e">ID</span>: <span style="color:#a6e22e">id</span>}
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">exists</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">articleService</span>.<span style="color:#a6e22e">ExistByID</span>()
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">appG</span>.<span style="color:#a6e22e">Response</span>(<span style="color:#a6e22e">http</span>.<span style="color:#a6e22e">StatusOK</span>, <span style="color:#a6e22e">e</span>.<span style="color:#a6e22e">ERROR_CHECK_EXIST_ARTICLE_FAIL</span>, <span style="color:#66d9ef">nil</span>)
</span></span><span style="display:flex;"><span>		<span style="color:#66d9ef">return</span>
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">if</span> !<span style="color:#a6e22e">exists</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">appG</span>.<span style="color:#a6e22e">Response</span>(<span style="color:#a6e22e">http</span>.<span style="color:#a6e22e">StatusOK</span>, <span style="color:#a6e22e">e</span>.<span style="color:#a6e22e">ERROR_NOT_EXIST_ARTICLE</span>, <span style="color:#66d9ef">nil</span>)
</span></span><span style="display:flex;"><span>		<span style="color:#66d9ef">return</span>
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">article</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">articleService</span>.<span style="color:#a6e22e">Get</span>()
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">appG</span>.<span style="color:#a6e22e">Response</span>(<span style="color:#a6e22e">http</span>.<span style="color:#a6e22e">StatusOK</span>, <span style="color:#a6e22e">e</span>.<span style="color:#a6e22e">ERROR_GET_ARTICLE_FAIL</span>, <span style="color:#66d9ef">nil</span>)
</span></span><span style="display:flex;"><span>		<span style="color:#66d9ef">return</span>
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">appG</span>.<span style="color:#a6e22e">Response</span>(<span style="color:#a6e22e">http</span>.<span style="color:#a6e22e">StatusOK</span>, <span style="color:#a6e22e">e</span>.<span style="color:#a6e22e">SUCCESS</span>, <span style="color:#a6e22e">article</span>)
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>这里有几个值得变动点，主要是在内部增加了错误返回，如果存在错误则直接返回。另外进行了分层，业务逻辑内聚到了 service 层中去，而 routers/api（controller）显著减轻，代码会更加的直观</p>
<p>例如 service/article_service 下的 <code>articleService.Get()</code> 方法：</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">func</span> (<span style="color:#a6e22e">a</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">Article</span>) <span style="color:#a6e22e">Get</span>() (<span style="color:#f92672">*</span><span style="color:#a6e22e">models</span>.<span style="color:#a6e22e">Article</span>, <span style="color:#66d9ef">error</span>) {
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">var</span> <span style="color:#a6e22e">cacheArticle</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">models</span>.<span style="color:#a6e22e">Article</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">cache</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">cache_service</span>.<span style="color:#a6e22e">Article</span>{<span style="color:#a6e22e">ID</span>: <span style="color:#a6e22e">a</span>.<span style="color:#a6e22e">ID</span>}
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">key</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">cache</span>.<span style="color:#a6e22e">GetArticleKey</span>()
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">gredis</span>.<span style="color:#a6e22e">Exists</span>(<span style="color:#a6e22e">key</span>) {
</span></span><span style="display:flex;"><span>		<span style="color:#a6e22e">data</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">gredis</span>.<span style="color:#a6e22e">Get</span>(<span style="color:#a6e22e">key</span>)
</span></span><span style="display:flex;"><span>		<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
</span></span><span style="display:flex;"><span>			<span style="color:#a6e22e">logging</span>.<span style="color:#a6e22e">Info</span>(<span style="color:#a6e22e">err</span>)
</span></span><span style="display:flex;"><span>		} <span style="color:#66d9ef">else</span> {
</span></span><span style="display:flex;"><span>			<span style="color:#a6e22e">json</span>.<span style="color:#a6e22e">Unmarshal</span>(<span style="color:#a6e22e">data</span>, <span style="color:#f92672">&amp;</span><span style="color:#a6e22e">cacheArticle</span>)
</span></span><span style="display:flex;"><span>			<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">cacheArticle</span>, <span style="color:#66d9ef">nil</span>
</span></span><span style="display:flex;"><span>		}
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">article</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">models</span>.<span style="color:#a6e22e">GetArticle</span>(<span style="color:#a6e22e">a</span>.<span style="color:#a6e22e">ID</span>)
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#66d9ef">return</span> <span style="color:#66d9ef">nil</span>, <span style="color:#a6e22e">err</span>
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">gredis</span>.<span style="color:#a6e22e">Set</span>(<span style="color:#a6e22e">key</span>, <span style="color:#a6e22e">article</span>, <span style="color:#ae81ff">3600</span>)
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">article</span>, <span style="color:#66d9ef">nil</span>
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>而对于 gorm 的 错误返回设置，只需要修改 models/article.go 如下:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-go" data-lang="go"><span style="display:flex;"><span><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">GetArticle</span>(<span style="color:#a6e22e">id</span> <span style="color:#66d9ef">int</span>) (<span style="color:#f92672">*</span><span style="color:#a6e22e">Article</span>, <span style="color:#66d9ef">error</span>) {
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">var</span> <span style="color:#a6e22e">article</span> <span style="color:#a6e22e">Article</span>
</span></span><span style="display:flex;"><span>	<span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">db</span>.<span style="color:#a6e22e">Where</span>(<span style="color:#e6db74">&#34;id = ? AND deleted_on = ? &#34;</span>, <span style="color:#a6e22e">id</span>, <span style="color:#ae81ff">0</span>).<span style="color:#a6e22e">First</span>(<span style="color:#f92672">&amp;</span><span style="color:#a6e22e">article</span>).<span style="color:#a6e22e">Related</span>(<span style="color:#f92672">&amp;</span><span style="color:#a6e22e">article</span>.<span style="color:#a6e22e">Tag</span>).<span style="color:#a6e22e">Error</span>
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> <span style="color:#f92672">&amp;&amp;</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#a6e22e">gorm</span>.<span style="color:#a6e22e">ErrRecordNotFound</span> {
</span></span><span style="display:flex;"><span>		<span style="color:#66d9ef">return</span> <span style="color:#66d9ef">nil</span>, <span style="color:#a6e22e">err</span>
</span></span><span style="display:flex;"><span>	}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>	<span style="color:#66d9ef">return</span> <span style="color:#f92672">&amp;</span><span style="color:#a6e22e">article</span>, <span style="color:#66d9ef">nil</span>
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>习惯性增加 .Error，把控绝大部分的错误。另外需要注意一点，在 gorm 中，查找不到记录也算一种 “错误” 哦</p>
<h2 id="最后">最后</h2>
<p>显然，本章节并不是你跟着我敲系列。我给你的课题是 “实现 Redis 缓存并优化既有的业务逻辑代码”</p>
<p>让其能够不断地适应业务的发展，让代码更清晰易读，且呈层级和结构性</p>
<p>如果有疑惑，可以到 <a href="https://github.com/EDDYCJY/go-gin-example">go-gin-example</a> 看看我是怎么写的，你是怎么写的，又分别有什么优势、劣势，取长补短一波？</p>
<h2 id="参考">参考</h2>
<h3 id="本系列示例代码">本系列示例代码</h3>
<ul>
<li><a href="https://github.com/EDDYCJY/go-gin-example">go-gin-example</a></li>
</ul>
<h3 id="推荐阅读">推荐阅读</h3>
<ul>
<li><a href="https://coolshell.cn/articles/17757.html">如何重构“箭头型”代码</a></li>
</ul>
<h2 id="关于">关于</h2>
<h3 id="修改记录">修改记录</h3>
<ul>
<li>第一版：2018 年 02 月 16 日发布文章</li>
<li>第二版：2019 年 10 月 01 日修改文章</li>
</ul>
<h2 id="heading">？</h2>
<p>如果有任何疑问或错误，欢迎在 <a href="https://github.com/EDDYCJY/blog">issues</a> 进行提问或给予修正意见，如果喜欢或对你有所帮助，欢迎 Star，对作者是一种鼓励和推进。</p>
<h3 id="我的公众号">我的公众号</h3>
<p><img src="https://image.eddycjy.com/8d0b0c3a11e74efd5fdfd7910257e70b.jpg" alt="image"></p>


                                        
                                        
                                        
                                        <div class="rp4wp-related-posts">
                                            <h3>相关文章</h3>
                                            <ul>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/gin/2018-05-27-config-upload/">「连载十二」优化配置结构及实现图片上传</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/gin/2018-04-29-cron/">「连载十一」Cron定时任务</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/gin/2018-04-15-gorm-callback/">「连载十」定制 GORM Callbacks</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/gin/2018-03-26-cgo/">「番外」Golang 交叉编译</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.asia/posts/posts/go/gin/2018-03-24-golang-docker/">「连载九」将Golang应用部署到Docker</a>
                                                    </div>
                                                </li>
                                                
                                            </ul>
                                        </div>
                                        
                                        
                                    </div>

                                    
                                    
                                    

                                    
                                    <div class="post-meta">
                                        
                                        
                                        <div class="post-tags">
                                            <ul>
                                            
                                            <li>
                                                <a href="/tags/go" title="View all posts tagged match">go</a>
                                            </li>
                                            
                                            <li>
                                                <a href="/tags/gin" title="View all posts tagged match">gin</a>
                                            </li>
                                            
                                            </ul>
                                        </div>
                                        
                                        
                                        <nav class="further-reading">
                                            
                                            <div class="previous">
                                                <span>&lt;&lt; Prev</span>
                                                <a href="https://www.lican.asia/posts/posts/go/gin/2018-05-27-config-upload/"
                                                    rel="prev">「连载十二」优化配置结构及实现图片上传</a> </div>
                                            
                                            
                                            <div class="next">
                                                <span>Next >></span>
                                                <a href="https://www.lican.asia/posts/posts/go/talk/2018-06-07-go-redis-protocol/">用 Go 来了解一下 Redis 通讯协议</a> 
                                            </div>
                                            
                                        </nav>
                                    </div>
                                    
                                    

                                    
                                    
                                    

                                </div>
                            </article>
                        </div>
                    </div>
                </section>
                <aside class="sidebar sidebar-primary" id="sidebar-primary" role="complementary">
    <h1 class="screen-reader-text">Sidebar</h1>
    

    
    
    <section id="text-2" class="widget widget_text">
        <div class="textwidget">
            
            <div id="profile">
                <div id="profile_picture"><img src="https://www.lican.asia/logo/logo.png"></div>
                <div id="profile_intro">
                    <p><span class="name">Lican</span></p>
                    <p class="intro">全栈开发者，爱好造轮子。</p>
                </div>
            </div>
            
            <p>
                <script type="text/javascript">
                    (function ($) {
                        $(document).ready(function () {
                            var menuPrimaryContainer = $('#menu-primary-container');
                            var profile = $('#text-2');
                            $('#toggle-navigation').click(function () {
                                if (menuPrimaryContainer.hasClass('open')) {
                                    profile.removeClass('open');
                                } else {
                                    profile.addClass('open');
                                }
                            });
                        });
                    })(jQuery);
                </script>
            </p>
        </div>
    </section>
    
    
    
    
    
    <section id="text-5" class="widget widget_text">
        <h2 class="widget-title">开源项目</h2>
        <div class="textwidget">
            <div id="projects" style="line-height: 22px;">
                
                <a href="https://github.com/idoubi/gonews"
                    target="_blank">gonews</a>: &nbsp;Daily news for golang<br>
                
                <a href="https://github.com/idoubi/sql2struct"
                    target="_blank">sql2struct</a>: &nbsp;Generate go struct according to SQL<br>
                
                <a href="https://github.com/idoubi/goz"
                    target="_blank">goz</a>: &nbsp;Request library used in golang<br>
                
        </div>
    </section>
    
    

    
    
    
    
    <section id="qrcode" class="widget widget_media_image">
        <h2 class="widget-title">微信公众号</h2>
        <img width="258" height="258"
            src="https://www.lican.asia/wechat/lican.png"
            class="image wp-image-5514  attachment-full size-full" alt=""
            style="max-width: 100%; height: auto;"
            sizes="(max-width: 258px) 100vw, 258px">
    </section>
    
    

    
    
    

    
    
    

    
    
    
    
</aside>
            </div>
        </div>

        <footer id="site-footer" class="site-footer" role="contentinfo">
    <div class="max-width">
    </div>
    <div class="footer">
        <div id="footercontent">
            © lican.asia All rights reserved<br/>
            Built with Hugo Theme <a href="https://github.com/idoubi/hugo-theme-period" target="_blank">Period</a>
        </div>
    </div>
</footer>

<script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?e8351b6d4626d5881d439ea1f6184baa";
      var s = document.getElementsByTagName("script")[0]; 
      s.parentNode.insertBefore(hm, s);
    })();
</script>
    
    
    </div>
    
</body>

</html>